import { Component, OnInit, ViewChild, ViewContainerRef, ComponentRef, ComponentFactoryResolver, EventEmitter } from '@angular/core';
import { ExtractionService } from './extract.service';
import { ContractAccountComponent } from "../modal/contract-account/contract-account.component";
import { ContractServiceComponent } from "../modal/contract-service/contract-service.component";
import { ExtractAccountComponent } from "../modal/extract-account/extract-account.component";
import { ExtractServiceComponent } from "../modal/extract-service/extract-service.component";
import { ServiceCheckComponent } from "../modal/service-check/service-check.component";
import { PaginationModel } from 'app/widgets/pagination';
import { environment } from '../../../../environments/environment';
import { DataService } from '../../../services/data.service';
import * as _ from 'lodash';

@Component({
  selector: 'app-extract',
  templateUrl: './extract.component.html',
  styleUrls: ['./extract.component.scss'],
  providers: [ExtractionService]
})
export class ExtractComponent implements OnInit {
  // lodash
  public _: any = _;

  // 服务抽取模版
  @ViewChild("extractService", { read: ViewContainerRef })
  extractService: ViewContainerRef;
  extractServiceComponent: ComponentRef<ExtractServiceComponent>;
  // 服务审核模版
  @ViewChild("serviceCheck", { read: ViewContainerRef })
  serviceCheck: ViewContainerRef;
  serviceCheckComponent: ComponentRef<ServiceCheckComponent>;
  // 核算抽取模版
  @ViewChild("extractAccount", { read: ViewContainerRef })
  extractAccount: ViewContainerRef;
  extractAccountComponent: ComponentRef<ExtractAccountComponent>;
  // 合同服务模版
  @ViewChild("contractService", { read: ViewContainerRef })
  contractService: ViewContainerRef;
  contractServiceComponent: ComponentRef<ContractServiceComponent>;
  // 合同核算模版
  @ViewChild("contractAccount", { read: ViewContainerRef })
  contractAccount: ViewContainerRef;
  contractAccountComponent: ComponentRef<ContractAccountComponent>;

  // 字典值
  public dictionaryList: any = {
    STOP_TYPE: []
  };
  // 菜单数据
  public menuData: any;
  // 菜单权限set
  public menuResourceSet: any = [];
  // 条目抽取列表数据
  public extractList: any;
  // 条目抽取列表全选
  public isCheckedAll: any = false;
  // 条目抽取列表请求体
  public getExtractPost = {
    pageIndex: 1,
    pageSize: 10,
    sFundCode: '',
    sFullName: ''
  };
  // 条目抽取列表页配置
  public extractPageInfo: PaginationModel = {
    currentPageNum: 1,
    pageSize: 10,
    totalPages: 1,
    total: 0,
    pagesShow: 5,
    startRow: 0,
    endRow: 0,
    pageList: [5, 10, 25, 50, 100]
  };

  constructor(
    public resolver: ComponentFactoryResolver,
    public extractionService: ExtractionService,
    public dataService: DataService
  ) {

  }

  ngOnInit() {
    let that = this;
    this.getExtractList();
    // 权限处理
    this.dataService.initTree.subscribe(data => {
      if (data) {
        let SessionMenuData = sessionStorage.getItem('menu');
        this.menuData = JSON.parse(SessionMenuData);
        this.menuResourceSet = [];
        _.forEach(this.menuData, (item, index) => {
          if (item.sName == '条目管理') {
            _.forEach(item.children, (it, idx) => {
              if (it.sName == '条目抽取管理') {
                that.menuResourceSet = it.resourceSet;
                sessionStorage.setItem('btn-entry', this.menuResourceSet);
              }
            })
          }
        })
      }
    })
    let SessionMenuData = sessionStorage.getItem('menu');
    this.menuData = JSON.parse(SessionMenuData);
    this.menuResourceSet = [];
    _.forEach(this.menuData, (item, index) => {
      if (item.sName == '条目管理') {
        _.forEach(item.children, (it, idx) => {
          if (it.sName == '条目抽取管理') {
            that.menuResourceSet = it.resourceSet;
            sessionStorage.setItem('btn-entry', this.menuResourceSet);
          }
        })
      }
    })
    this.dataService.entryEmitter = new EventEmitter();
    this.dataService.entryEmitter.subscribe((value: any) => {
      if (value) {
        switch (value) {
          case 'extractService':
            window['$']('#modal1').modal('hide');
            that.getExtractList();
            break;
          case 'serviceCheck':
            window['$']('#modal2').modal('hide');
            that.getExtractList();
            break;
          case 'extractAccount':
            window['$']('#modal3').modal('hide');
            that.getExtractList();
            break;
          case 'contractService':
            window['$']('#modal4').modal('hide');
            that.getExtractList();
            break;
          case 'contractAccount':
            window['$']('#modal5').modal('hide');
            that.getExtractList();
            break;
        }
      }
    })
  }
  // 条目抽取列表
  getExtractList(pageNum?, pageSize?) {
    let that = this;
    this.isCheckedAll = false;
    this.getExtractPost.sFundCode = _.trim(this.getExtractPost.sFundCode);
    this.getExtractPost.sFullName = _.trim(this.getExtractPost.sFullName);
    this.getExtractPost.pageIndex = pageNum ? pageNum : this.extractPageInfo.currentPageNum;
    this.getExtractPost.pageSize = pageSize ? pageSize : this.extractPageInfo.pageSize;
    // console.log(this.getExtractPost)
    this.extractionService.getExtractList(this.getExtractPost).subscribe(data => {
      if (data) {

        that.extractList = data.list;
        // console.log(that.extractList)
        that.extractPageInfo.currentPageNum = data.pageNum;
        that.extractPageInfo.totalPages = data.pages;
        that.extractPageInfo.total = data.total;
        that.extractPageInfo.startRow = data.startRow;
        that.extractPageInfo.endRow = data.endRow;
      }
    });
  }
  // 条目抽取个数分页
  extractpageSizeChange(pageSize: number) {
    if (pageSize !== this.extractPageInfo.pageSize) {
      this.extractPageInfo.pageSize = pageSize;
      this.getExtractList();
    }
  }
  // 条目抽取条数分页
  extractPageNavigation(currentPageNum: number) {
    this.extractPageInfo.currentPageNum = currentPageNum;
    this.getExtractList(this.extractPageInfo.currentPageNum, this.extractPageInfo.pageSize);
  }
  // 条目抽取列表全选
  extractCheckedAll() {
    if (this.isCheckedAll) {
      _.forEach(this.extractList, item => {
        item.isChecked = true;
      });
    } else {
      _.forEach(this.extractList, item => {
        item.isChecked = false;
      });
    }
  }
  // 条目抽取列表是否全选
  ctrlExtractCheckAll() {
    let that = this;
    let checkList = [];
    _.forEach(this.extractList, item => {
      if (item.isChecked == true) {
        checkList.push(item);
      }
    })
    if (checkList.length == this.extractList.length) {
      this.isCheckedAll = true;
    } else {
      this.isCheckedAll = false;
    }
  }
  // 导出
  exportExcel() {
    let that = this;
    let checkedItem = [];
    _.forEach(this.extractList, item => {
      if (item.isChecked) {
        checkedItem.push(item.nFundNo);
      }
    })
    // let converItem: any = checkedItem.join(',');
    let getBody = {
      "nFundNoList": checkedItem,
      "sFullName": this.getExtractPost.sFullName,
      "sFundCode": this.getExtractPost.sFundCode
    }
    // const iframe = window['$']("<iframe id='downloadiframe'>");
    // iframe.attr('style', 'display:none');
    // //  转码，兼容ie
    // getBody.sFullName = encodeURI(getBody.sFullName);
    // iframe.attr('src', environment.server + '/pms/v1/item/export/pensionInfo?token=' + sessionStorage.getItem('token') + '&nFundNoList=' + getBody.nFundNoList + '&sFundCode=' + getBody.sFundCode + '&sFullName=' + getBody.sFullName);
    // window['$']('body').append(iframe);
    // setTimeout("$('#downloadiframe').remove()", 60000);
    // 请求Url
    let postUrl = environment.server + '/pms/v1/pension/basicInfo/export/pensionDeptList?token=' + sessionStorage.getItem('token');
    // 导出
    this.extractionService.exportTarget(postUrl, getBody, '条目管理-条目抽取列表');
  }
  // 模态框
  showModal(id) {
    var that = this;
    let Id = '#modal' + id;
    let checkedItem = [];
    let entryInfo: any = {};
    _.forEach(this.extractList, item => {
      if (item.isChecked) {
        checkedItem.push(item);
      }
    })
    if (checkedItem.length == 1) {
      entryInfo = checkedItem[0];
      switch (id) {
        case '1':
          //判断服务条目是否为待审核、未抽取状态、审核不通过
          if (entryInfo.sServiceItem == '3' || entryInfo.sServiceItem == '1' || entryInfo.sServiceItem == '0') {
            that.showExtractService(entryInfo);
            window['$'](Id).modal('show');
          } else {
            window['swal']("注意", "该合同已完成服务条目抽取!", "warning")
          }
          break;
        case '2':
          //判断服务条目是否为待审核状态
          if (entryInfo.sServiceItem == '1') {
            that.showServiceCheck(entryInfo);
            window['$'](Id).modal('show');
          } else if (entryInfo.sServiceItem == '3' || entryInfo.sServiceItem == '2') {
            window['swal']("注意", "不能选择审核过的数据进行审核!", "warning")
          } else if (entryInfo.sServiceItem == '0') {
            window['swal']("注意", "请先抽取服务类条目!", "warning")
          }
          break;
        case '3':
          //判断核算条目是否为待审核或者未抽取状态
          if (entryInfo.sAccountItem == '0') {
            console.log(entryInfo)
            that.showExtractAccount(entryInfo);
            window['$'](Id).modal('show');
          } else {
            window['swal']("注意", "请选择一条核算条目为未抽取的数据!", "warning")
          }
          break;
        case '4':
          if (entryInfo.sServiceItem == '2') {
            that.showContractService(entryInfo);
            window['$'](Id).modal('show');
          } else {
            window['swal']("注意", "请选择一条服务条目为审核通过的数据!", "warning")
          }
          break;
        case '5':
          if (entryInfo.sAccountItem == '1') {
            that.showContractAccount(entryInfo);
            window['$'](Id).modal('show');
          } else {
            window['swal']("注意", "请选择一条核算条目为已抽取的数据!", "warning")
          }
          break;

      }
    } else {
      switch (id) {
        case '1':
          window['swal']("提示", "请选择一条产品进行抽取", "warning");
          break;
        case '3':
          window['swal']("提示", "请选择一条产品进行抽取", "warning");
          break;
        case '2':
          window['swal']("提示", "请选择一条产品进行审核", "warning");
          break;
        case '4':
          window['swal']("提示", "请选择一条产品进行查看!", "warning");
          break;
        case '5':
          window['swal']("提示", "请选择一条产品进行查看!", "warning");
          break;
      }

    }

  }
  // 服务抽取模版
  showExtractService(item) {
    if (this.extractServiceComponent && this.extractServiceComponent.instance) {
      this.extractServiceComponent.destroy();
    }
    const extractServiceComponent = this.resolver.resolveComponentFactory(ExtractServiceComponent);
    this.extractServiceComponent = this.extractService.createComponent(extractServiceComponent);
    this.extractServiceComponent.instance.extractInfo = item;
  }
  // 服务审核模版
  showServiceCheck(item) {
    if (this.serviceCheckComponent && this.serviceCheckComponent.instance) {
      this.serviceCheckComponent.destroy();
    }
    const serviceCheckComponent = this.resolver.resolveComponentFactory(ServiceCheckComponent);
    this.serviceCheckComponent = this.serviceCheck.createComponent(serviceCheckComponent);
    this.serviceCheckComponent.instance.serviceCheckInfo = item;

  }
  // 核算抽取模版
  showExtractAccount(item) {
    if (this.extractAccountComponent && this.extractAccountComponent.instance) {
      this.extractAccountComponent.destroy();
    }
    const extractAccountComponent = this.resolver.resolveComponentFactory(ExtractAccountComponent);
    this.extractAccountComponent = this.extractAccount.createComponent(extractAccountComponent);
    this.extractAccountComponent.instance.extractAccountInfo = item;
  }
  // 合同服务模版
  showContractService(item) {
    if (this.contractServiceComponent && this.contractServiceComponent.instance) {
      this.contractServiceComponent.destroy();
    }
    const contractServiceComponent = this.resolver.resolveComponentFactory(ContractServiceComponent);
    this.contractServiceComponent = this.contractService.createComponent(contractServiceComponent);
    this.contractServiceComponent.instance.contractBody = item;
  }
  // 合同核算模版
  showContractAccount(item) {
    if (this.contractAccountComponent && this.contractAccountComponent.instance) {
      this.contractAccountComponent.destroy();
    }
    const contractAccountComponent = this.resolver.resolveComponentFactory(ContractAccountComponent);
    this.contractAccountComponent = this.contractAccount.createComponent(contractAccountComponent);
    this.contractAccountComponent.instance.contractBody = item;
  }
  //更新-服务条目审核撤销
  revokeServiceCheck() {
    let that = this;
    let checkedItem = [];
    _.forEach(this.extractList, item => {
      if (item.isChecked) {
        checkedItem.push(item);
      }
    })
    if (checkedItem.length < 1) {
      window['swal']("注意", "请选择一条条目进行撤销!", "warning")
    } else if (checkedItem.length == 1) {
      if (checkedItem[0].sServiceItem == '2') {
        window["swal"]({
          title: "注意",
          text: "是否确定撤销条目服务审核",
          type: "warning",
          confirmButtonText: "确认",
          cancelButtonText: "取消",
          showCancelButton: true,
          closeOnConfirm: false,
          closeOnCancel: true,
          showLoaderOnConfirm: true
        },
          function (isConfirm) {
            if (isConfirm) {
              that.extractionService.revoke(checkedItem[0].nFundNo).subscribe(data => {
                if (data) {
                  window['swal']("提示", "撤销完成!", "success")
                  that.getExtractList();
                }
              })
            }
          })
      } else {
        window['swal']("注意", "请选择服务条目为审核通过的数据进行撤销!", "warning")
      }
    } else if (checkedItem.length > 1) {
      window['swal']("注意", "只能选择一条条目进行撤销!", "warning")
    }
  }
  // 点击表格头排序
  orderData(colName) {
    let listDataAsc = _.orderBy(this.extractList, [colName], ["asc"]);
    if (JSON.stringify(this.extractList) == JSON.stringify(listDataAsc)) {
      listDataAsc = _.orderBy(this.extractList, [colName], ["desc"]);
    }
    this.extractList = listDataAsc;
  }
}
